<template>
  <div class="wrapper">
    <el-form inline>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="起始日期"
          end-placeholder="截止日期"
          :shortcuts="shortcuts"
        />
      </el-form-item>
      <el-form-item label="时间排序">
        <el-radio-group v-model="queryOrder">
          <el-radio-button value="ASC">升序</el-radio-button>
          <el-radio-button value="DESC">降序</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="handleQuery"
          type="primary"
          icon="Search"
          style="margin-left: 24px"
          >查询</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import axios from "axios";
import dateFormat from "@/utils/dateFormat.js";
import useCapacityStore from "@/store/capacity.js";
const capacityStore = useCapacityStore();

const dateRange = ref("");
const queryOrder = ref("DESC");

const shortcuts = [
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "近90天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

const handleQuery = () => {
  let start = dateFormat("YYYY-mm-dd", dateRange.value[0]);
  let end = dateFormat("YYYY-mm-dd", dateRange.value[1]);
  let options = { start, end, order: queryOrder.value, setted: true };
  capacityStore.historyQueryOptions = options;
  console.log("handleQuery", options);
  axios
    .post("api/capacity_record_query.php", options)
    .then((response) => {
      console.log(response.data);
      capacityStore.historyRecords = response.data.payload;
      capacityStore.historyQueryOptions = options;
    })
    .catch((error) => {
      console.error(error);
    });
};

onMounted(() => {
  if (capacityStore.historyQueryOptions.setted) {
    dateRange.value = [
      new Date(capacityStore.historyQueryOptions.start),
      new Date(capacityStore.historyQueryOptions.end),
    ];
  } else {
    dateRange.value = [new Date(), new Date()];
  }
});
</script>

<style scoped>
.wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px 12px 24px;
}
</style>
